package com.itheima.stock.service.impl;

import com.alibaba.excel.EasyExcel;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.gson.Gson;
import com.itheima.stock.domain.Stock4EvrDayDomain;
import com.itheima.stock.domain.Stock4MinuteDomain;
import com.itheima.stock.domain.StockExcelDomain;
import com.itheima.stock.domain.StockUpdownDomain;
import com.itheima.stock.entity.StockBlockRtInfo;
import com.itheima.stock.entity.StockBusiness;
import com.itheima.stock.entity.StockMarketIndexInfo;
import com.itheima.stock.entity.StockMarketLogPrice;
import com.itheima.stock.enums.CodeEnum;
import com.itheima.stock.mapper.*;
import com.itheima.stock.properties.MarketProperties;
import com.itheima.stock.response.ResponseResult;
import com.itheima.stock.service.StockService;
import com.itheima.stock.util.DateTimeUtil;
import com.itheima.stock.vo.InnerMarketVO;
import com.itheima.stock.vo.resp.PageResult;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import net.sf.jsqlparser.expression.DateTimeLiteralExpression;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author zby
 * @created 2024-06-23 16:34
 * @description  股票业务实现类
 */
@Slf4j
@Service
public class StockServiceImpl implements StockService {
    @Autowired
    private StockBlockRtInfoMapper stockBlockRtInfoMapper;
    @Autowired
    private StockRtInfoMapper stockRtInfoMapper;

    private final StockBusinessMapper stockBusinessMapper;
    private final MarketProperties marketProperties;
    private final StockMarketIndexInfoMapper stockMarketIndexInfoMapper;
    private final StockMarketLogPriceMapper stockMarketLogPriceMapper;

    public StockServiceImpl(StockBusinessMapper stockBusinessMapper, MarketProperties marketProperties, StockMarketIndexInfoMapper stockMarketIndexInfoMapper, StockMarketLogPriceMapper stockMarketLogPriceMapper) {
        this.stockBusinessMapper = stockBusinessMapper;
        this.marketProperties = marketProperties;
        this.stockMarketIndexInfoMapper = stockMarketIndexInfoMapper;
        this.stockMarketLogPriceMapper = stockMarketLogPriceMapper;
    }


    @Override
    public List<StockBusiness> getStockBusiness() {

        return stockBusinessMapper.selectAll();
    }

    @Override
    public List<InnerMarketVO> innerIndexAll() {
        // 1. 获取国内大盘指数编码集合
        List<String> ids = marketProperties.getInner();
        // 2. 获取最近的有效的股票交易时间
        LocalDateTime last = DateTimeUtil.getLastDateTime4Stock(LocalDateTime.now());
        // mock data
        String mockDate = "20211226105600";
        last = LocalDateTime.parse(mockDate, DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
        // 3. 查询
        // 3.1 根据大盘编码和日期查询 股票大盘数据详情表
        List<StockMarketIndexInfo> marketIndexInfoList = stockMarketIndexInfoMapper.selectByIdsAndDateTime(ids, last);
        // 3.2 根据大盘编码和日期查询 股票大盘 开盘价与前收盘价流水表
        LocalDate localDate = last.toLocalDate();
        List<StockMarketLogPrice> marketLogPriceList = stockMarketLogPriceMapper.selectByIdsAndDateTime(ids, localDate);
        //4. 组装数据
        return marketIndexInfoList.stream().map((marketIndexInfo) -> {
                    InnerMarketVO vo = InnerMarketVO.builder()
                            .code(marketIndexInfo.getMarkId())
                            .name(marketIndexInfo.getMarkName())
                            .curDate(new SimpleDateFormat("yyyyMMdd").format(marketIndexInfo.getCurTime()))
                            .tradeAmt(marketIndexInfo.getTradeAccount())
                            .tradeVol(marketIndexInfo.getTradeVolume())
                            .tradePrice(marketIndexInfo.getCurrentPrice())
                            .upDown(marketIndexInfo.getUpdownRate())
                            .build();
                    marketLogPriceList.forEach((marketLogPrice) -> {
                        if (marketLogPrice.getMarketCode().equals(marketIndexInfo.getMarkId())) {
                            vo.setOpenPrice(marketLogPrice.getOpenPrice());
                            vo.setPreClosePrice(marketLogPrice.getPreClosePrice());
                        }
                    });
                    return vo;
                }
        ).toList();
    }

    @Override
    public ResponseResult<List<StockBlockRtInfo>> sectorAllLimit() {

        //1.调用mapper接口获取数据 TODO 优化 避免全表查询 根据时间范围查询，提高查询效率
        List<StockBlockRtInfo> infos=stockBlockRtInfoMapper.sectorAllLimit();

        //2.组装数据
        if (CollectionUtils.isEmpty(infos)) {
            return ResponseResult.error(CodeEnum.NO_RESPONSE_DATA);
        }
        return ResponseResult.ok(infos);
    }

    @Override
    public ResponseResult<List<StockUpdownDomain>> stockIncreaseLimit() {
        //1.直接调用mapper查询前10的数据 TODO 以时间顺序取前10
        //优化：
        //获取当前最近有效时间
        //Date curDateTime = DateTimeUtil.getLastDateString4Stock(DateTimeLiteralExpression.DateTime.now()).toDate();
        //mock数据
        String mockStr="2021-12-27 09:47:00";

        LocalDateTime localDateTime = LocalDateTime.parse(mockStr, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        Date curDateTime = DateTimeUtil.toDate(localDateTime);

        List<StockUpdownDomain> infos=stockRtInfoMapper.stockIncreaseLimit(curDateTime);
        //2.判断是否有数据
        if (CollectionUtils.isEmpty(infos)) {
            return ResponseResult.error(CodeEnum.NO_RESPONSE_DATA);
        }
        return ResponseResult.ok(infos);
    }

    @Override
    public ResponseResult<PageResult<StockUpdownDomain>> stockPage(Integer page, Integer pageSize) {
        //1.设置分页参数
        PageHelper.startPage(page,pageSize);
        //2.通过mapper查询
        List<StockUpdownDomain> infos= stockRtInfoMapper.stockAll();
        if (CollectionUtils.isEmpty(infos)) {
            return ResponseResult.error(CodeEnum.NO_RESPONSE_DATA);
        }
        //3.封装到PageResult下
        //3.1 封装PageInfo对象
        PageInfo<StockUpdownDomain> listPageInfo = new PageInfo<StockUpdownDomain>(infos);
        //3.2 将PageInfo转PageResult
        PageResult<StockUpdownDomain> pageResult = new PageResult<>(listPageInfo);
        //4.封装R响应对象
        return ResponseResult.ok(pageResult);
    }

    @Override
    public ResponseResult<Map> upDownCount() {
        //1.获取股票最近的有效交易日期,精确到秒
        //DateTimeLiteralExpression.DateTime curDateTime = DateTimeUtil.getLastDate4Stock(DateTimeLiteralExpression.DateTime.now());
        //当前最近有效期
        //Date curTime = curDateTime.toDate();
        //开盘日期
        //Date openTime = DateTimeUtil.getOpenDate(curDateTime).toDate();
        //TODO mock_data 后续数据实时获取时，注释掉
        String curTimeStr="20220106142500";
        //对应开盘日期 mock_data
        String openTimeStr="20220106092500";
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
        LocalDateTime curTime = LocalDateTime.parse(curTimeStr, formatter);
        LocalDateTime openTime = LocalDateTime.parse(openTimeStr, formatter);
        //2.统计涨停的数据 约定：1代表涨停 0：跌停
        List<Map> upCount= stockRtInfoMapper.upDownCount(curTime,openTime,1);
        //3.统计跌停的数据
        List<Map> downCount= stockRtInfoMapper.upDownCount(curTime,openTime,0);
        //4.组装数据到map
        HashMap<String, List<Map>> info = new HashMap<>();
        info.put("upList",upCount);
        info.put("downList",downCount);
        //5.响应
        return ResponseResult.ok(info);

    }

    @Override
    public void stockExport(HttpServletResponse response, Integer page, Integer pageSize) {
        try {
            //1.设置响应数据的类型:excel
            response.setContentType("application/vnd.ms-excel");
            //2.设置响应数据的编码格式
            response.setCharacterEncoding("utf-8");
            //3.设置默认的文件名称
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("stockRt", "UTF-8");
            //设置默认文件名称
            response.setHeader("content-disposition", "attachment;filename=" + fileName + ".xlsx");
            //4.分页查询股票数据
            PageHelper.startPage(page,pageSize);
            List<StockUpdownDomain> infos = this.stockRtInfoMapper.stockAll();
            Gson gson = new Gson();
            List<StockExcelDomain> excelDomains = infos.stream().map(info -> {
                StockExcelDomain domain=new StockExcelDomain();
                BeanUtils.copyProperties(info,domain);
                return domain;
            }).collect(Collectors.toList());
            //5.导出
            EasyExcel.write(response.getOutputStream(),StockExcelDomain.class).sheet("股票数据").doWrite(excelDomains);
        } catch (IOException e) {
            log.info("股票excel数据导出异常，当前页：{}，每页大小：{}，异常信息：{}",page,pageSize,e.getMessage());
        }
    }

    @Override
    public ResponseResult<Map> stockTradeVol4InnerMarket() {

        //1.获取最近的股票交易日时间，精确到分钟 T交易日
        //DateTime tDate = DateTimeUtil.getLastDate4Stock(DateTime.now());
        //Date tDateTime = tDate.toDate();
        //对应的开盘时间
        //Date tOpenTime = DateTimeUtil.getOpenDate(tDate).toDate();
        //TODO 后续注释掉 mock-data

        String tDateStr="20220103143000";
        Date tDateTime = DateTimeUtil.toDate(LocalDateTime.parse(tDateStr, DateTimeFormatter.ofPattern("yyyyMMddHHmmss")));
        //mock-data
        String openDateStr="20220103093000";
        Date tOpenTime = DateTimeUtil.toDate(LocalDateTime.parse(openDateStr, DateTimeFormatter.ofPattern("yyyyMMddHHmmss")));
        //获取T-1交易日
        //DateTime preTDate = DateTimeUtil.getPreviousTradingDay(tDate);
        //Date preTTime = preTDate.toDate();
        //Date preTOpenTime=DateTimeUtil.getOpenDate(preTDate).toDate();
        //TODO 后续注释掉 mock-data

        String preTStr="20220102143000";
        Date preTTime = DateTimeUtil.toDate(LocalDateTime.parse(preTStr, DateTimeFormatter.ofPattern("yyyyMMddHHmmss")));
        //mock-data
        String openDateStr2="20220102093000";
        Date preTOpenTime= DateTimeUtil.toDate(LocalDateTime.parse(openDateStr2, DateTimeFormatter.ofPattern("yyyyMMddHHmmss")));
        //2.获取T日的股票大盘交易量统计数据
        List<Map> tData=stockMarketIndexInfoMapper.stockTradeVolCount(marketProperties.getInner(),tOpenTime,tDateTime);
        //3.获取T-1的数据
        List<Map> preTData=stockMarketIndexInfoMapper.stockTradeVolCount(marketProperties.getInner(),preTOpenTime,preTTime);
        //4.组装数据
        HashMap<String, List<Map>> data = new HashMap<>();
        data.put("volList",tData);
        data.put("yesVolList",preTData);
        return ResponseResult.ok(data);
    }

    @Override
    public ResponseResult<Map> stockUpDownScopeCount() {
        //DateTime avlDateTime = DateTimeUtil.getLastDate4Stock(DateTime.now());
        //Date avlDate = avlDateTime.toDate();
        //TODO 后续删除 mock-data
        String  mockDate="20220106095500";
        Date avlDate = DateTimeUtil.toDate(LocalDateTime.parse(mockDate, DateTimeFormatter.ofPattern("yyyyMMddHHmmss")));
        LocalDateTime avlDateTime = DateTimeUtil.parseToLocalDateTime(mockDate, "yyyyMMddHHmmss");
        //2.查询
        List<Map> maps=stockRtInfoMapper.stockUpDownScopeCount(avlDate);
        List<String> upDownRange = marketProperties.getUpDownRange();
        //将list集合下的字符串映射成Map对象
        List<Map> orderMap = upDownRange.stream().map(key -> {
            Optional<Map> title = maps.stream().filter(map -> key.equals(map.get("title"))).findFirst();
            //判断对应的map是否存在
            Map tmp = null;
            if (title.isPresent()) {
                tmp = title.get();
            } else {
                tmp = new HashMap();
                tmp.put("title", key);
                tmp.put("count", 0);
            }
            return tmp;
        }).collect(Collectors.toList());
        //3.组装data
        HashMap<String, Object> data = new HashMap<>();
        data.put("time",avlDateTime.toString());
        data.put("infos",orderMap);
        //返回响应数据
        return ResponseResult.ok(data);
    }

    @Override
    public ResponseResult<List<Stock4MinuteDomain>> stockScreenTimeSharing(String code) {
        //1.获取最近有效的股票交易时间
        //DateTime curDateTime = DateTimeUtil.getLastDate4Stock(DateTime.now());
        //获取当前日期
        //Date curDate = curDateTime.toDate();
        //获取当前日期对应的开盘日期
        //Date openDate = DateTimeUtil.getOpenDate(curDateTime).toDate();
        //TODO 后续删除 mock-data
        String mockDate="20220106142500";
        Date curDate=DateTimeUtil.parseToDate(mockDate, "yyyyMMddHHmmss");
        String openDateStr="20220106093000";
        Date openDate=DateTimeUtil.parseToDate(openDateStr, "yyyyMMddHHmmss");
        List<Stock4MinuteDomain> maps= stockRtInfoMapper.stockScreenTimeSharing(code,openDate,curDate);
        //响应前端
        return ResponseResult.ok(maps);
    }

    @Override
    public ResponseResult<List<Stock4EvrDayDomain>> stockCreenDkLine(String code) {
        //获取当前日期前推20天
        //DateTime curDateTime = DateTimeUtil.getLastDate4Stock(DateTime.now());
        //当前时间节点
        //Date curTime = curDateTime.toDate();
        //前推20
        //Date pre20Day = curDateTime.minusDays(20).toDate();

        //TODO 后续删除
        String avlDate="20220101142500";
        Date curTime=DateTimeUtil.parseToDate(avlDate, "yyyyMMddHHmmss");
        String openDate="20210101093000";
        Date pre20Day=DateTimeUtil.parseToDate(openDate, "yyyyMMddHHmmss");
        // List<Stock4EvrDayDomain> infos = stockRtInfoMapper.stockCreenDkLine(code, pre20Day, curTime);
        //获取指定范围的收盘日期集合
        List<Date> closeDates=stockRtInfoMapper.getCloseDates(code,pre20Day,curTime);
        //根据收盘日期精准查询，如果不在收盘日期，则查询最新数据
        List<Stock4EvrDayDomain> infos= stockRtInfoMapper.getStockCreenDkLineData(code,closeDates);
        return ResponseResult.ok(infos);
    }
}
